<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryWarnList" :inline="true" label-width="68px">
        <el-form-item label="时间">
          <el-date-picker clearable v-model="timeList" type="datetimerange" range-separator="~"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                          @change="getWarn">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预警类型">
          <el-select
            v-model="queryWarnList.alarmsMode"
            placeholder="请选择预警类型"
            clearable
            :style="{ width: '100%' }"
            filterable
            @change="handleAlarmTypeChange"
          >
            <el-option
              v-for="item in alarmType"
              :key="item.warningType"
              :label="item.warningTypeName"
              :value="item.warningType"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="queryWarnList.drugName"
            placeholder="请输入商品名称进行查询"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="批次号">
          <el-input
            v-model="queryWarnList.vbatchNo"
            placeholder="请输入批号进行查询"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getWarnQuery"
          >查询
          </el-button
          >
          <el-button type="success" icon="el-icon-download" @click="exportExcel">导出excel</el-button>
          <el-button type="danger" icon="el-icon-refresh" @click="clearAll"
          >重置
          </el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        :data="alarmsList"
        border
        height="605px"
        :default-sort="{ prop: 'date', order: 'descending' }"
      >
        <el-table-column show-overflow-tooltip prop="product_code" label="商品编码" align="center"/>
        <el-table-column show-overflow-tooltip prop="product_name" label="商品名称" align="center"/>
        <el-table-column show-overflow-tooltip prop="sto_name" label="仓库名称" align="center"/>
        <el-table-column show-overflow-tooltip prop="batch_code" label="批号" align="center"/>
        <el-table-column show-overflow-tooltip prop="manufacturer" label="生产厂商" align="center"/>
        <el-table-column show-overflow-tooltip prop="pack_spec" label="商品规格" align="center"/>
        <el-table-column show-overflow-tooltip v-if="exp_date" prop="exp_date" label="有效期" align="center"/>
        <el-table-column show-overflow-tooltip v-if="num" prop="num" label="数量" align="center">
          <template #default="{row}">
            <el-tag type="danger">{{row.num}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="unit_code" label="货位" align="center"></el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[100, 150, 200, 500]"
        :total="total"
      />
    </el-card>
  </div>
</template>

<script>
import {getSkuAlarms, warningType} from "@/api/report/index.js";

export default {
  data() {
    return {
      queryWarnList: {
        alarmsValues: "",
        alarmsMode: 1, // 有效期
        batch_code: '',
        drugName: '',//药品名称
        startDate: '',
        endDate: '',
      },
      exp_date:false,
      num:false,
      timeList: [this.getDefaultStartDate(), this.getDefaultEndDate()], //时间合计
      pageNum: 1,
      pageSize: 100,
      total: 0,
      alarmsList: [],
      alarmType: [],
    };
  },
  created() {
    this.getTypeList(); // 初始化下拉框数据
  },
  watch: {
    alarmsList: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.exp_date = newVal.some(item => item.exp_date !== undefined && item.exp_date !== null && item.exp_date !== '');
          this.num = newVal.some(item => item.num !== undefined && item.num !== null && item.num !== '');
        } else {
          this.exp_date = false;
          this.num = false;
        }
      }
    }
  },
  methods: {
    //获取日期
    getDefaultStartDate() {
      const date = new Date()
      date.setMonth(date.getMonth() - 1)
      return this.formatDate(date)
    },
    getDefaultEndDate() {
      return this.formatDate(new Date())
    },
    //格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    //导出excel
    exportExcel() {
      this.download('warehouse/exportSkuAlarms', {
        ...this.queryWarnList,
      }, `预警管理.xlsx`)
    },
    // 分页大小变化
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNum = 1; // 重置到第一页
      this.getWarn()
    },
    // 当前页变化
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.getWarn();
    },
    // 获取下拉框数据
    async getTypeList() {
      try {
        const res = await warningType();
        this.alarmType = res.data;
        // 默认选择第一个选项
        if (this.alarmType.length > 0) {
          this.queryWarnList.alarmsMode = this.alarmType[0].warningType;
          this.queryWarnList.alarmsValues = this.alarmType[0].warningTime;
          this.getWarn(); // 初始化数据
        }
      } catch (error) {
        console.error("获取预警类型失败：", error);
      }
    },
    // 监听下拉框选择事件
    handleAlarmTypeChange(value) {
      const selectedOption = this.alarmType.find(
        (item) => item.warningType === value
      );
      this.queryWarnList.alarmsValues = selectedOption
        ? selectedOption.warningTime
        : "";
      this.getWarnQuery(); // 查询数据
    },
    // 查询数据
    async getWarn() {
      try {
        if (this.timeList && this.timeList[0]) {
          this.queryWarnList.startDate = this.timeList[0];
        } else {
          delete this.queryWarnList.startDate; // 如果时间为空，则删除该字段
        }
        if (this.timeList && this.timeList[1]) {
          this.queryWarnList.endDate = this.timeList[1];
        } else {
          delete this.queryWarnList.endDate; // 如果时间为空，则删除该字段
        }
        let param = {
          ...this.queryWarnList,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
        }
        const res = await getSkuAlarms(param);
        this.alarmsList = res.data.rows;
        this.total = res.data.total;
      } catch (error) {
        console.error("获取预警数据失败：", error);
      }
    },
    // 查询按钮事件
    getWarnQuery() {
      this.pageNum = 1; // 重置到第一页
      this.getWarn();
    },
    // 重置按钮事件
    clearAll() {
      this.queryWarnList = {
        alarmsValues: "",
        alarmsMode: 1, // 有效期
        vbatchNo: '',
        drugName: '',//药品名称
        startDate: '',
        endDate: '',
      }
      this.timeList = [this.getDefaultStartDate(), this.getDefaultEndDate()]//时间合计
      this.getWarn();
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.el-card {
  margin-bottom: 20px;
}

.el-pagination {
  float: right;
  margin: 20px;
}
</style>
